package com.supply.dl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supply.dl.R;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.bean.BaseItemBean;
import com.supply.dl.bean.BatchLocationNoticeBean;
import com.supply.dl.bean.InAndOutBoundLocationBean;
import com.supply.dl.bean.MaterielBatchWorkBean;
import com.supply.dl.bean.MaterielPositionInfoBean;
import com.supply.dl.bean.OperateFlagEnum;
import com.supply.dl.bean.OrderInAndOutBoundBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.WorkInfoBean;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.bean.request.ConfirmLocationNoticeDetailRequest;
import com.supply.dl.constant.Constants;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.CommonNormalAdapterUtil;
import com.supply.dl.utils.InterfaceUtil;
import com.supply.dl.utils.RecyclerViewUtil;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.widget.LoadTipFailedLayout;
import com.supply.dl.widget.adapter.CommonNormalAdapter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ${qianzhihe} on 2018/7/11.
 * 通知单批量作业界面
 */

public class BatchWorkActivity extends BaseActivity implements View.OnClickListener{

    /**
     * 加载框
     */
    @BindView(R.id.batch_work_main_loadView)
    LoadTipFailedLayout loadTipFailedLayout;

    @BindView(R.id.batch_work_main_tvSureWork)
    TextView tvSureWork;

    @BindView(R.id.common_materiel_position_info_showFirstValue)
    TextView showFirstValue;//物料编码
    @BindView(R.id.common_materiel_position_info_showSecondValue)
    TextView showSecondValue;//原料名称
    @BindView(R.id.common_materiel_position_info_showThirdValue)
    TextView showThirdValue;//总数
    @BindView(R.id.common_materiel_position_info_fourthTv)
    TextView showFourthTv;//未作业数量 Title
    @BindView(R.id.common_materiel_position_info_showFourthValue)
    TextView showFourthValue;//未作业数量

    /**
     * 物料列表
     */
    @BindView(R.id.batch_work_main_materielRecyclerView)
    MaxRecyclerView materielRecyclerView;
    CommonNormalAdapter materielAdapter;
    int materielAdapterFlag;
    List<BaseItemBean> itemMaterielList;

    List<BaseItemBean> itemList;

    int activityFlag;

    @BindView(R.id.batch_work_main_content_tvWorkInfo)
    TextView tvWorkInfo;//统一作业的信息：未作业 总数量：0件/8.44吨

    @BindView(R.id.batch_work_main_content_tvShowReservoirPosition)
    TextView tvShowReservoirPosition;//库位
    @BindView(R.id.batch_work_main_content_editShowStorehouse)
    TextView tvShowStorehouse;//仓库
    @BindView(R.id.batch_work_main_content_tvShowJobRecord)
    TextView tvShowJobRecord;//作业记录
    @BindView(R.id.batch_work_main_content_editShowRemarks)
    EditText editShowRemarks;//备注

    @BindView(R.id.batch_work_main_content_editShowNumberForPiece)
    EditText editShowNumberForPiece;//数量
    @BindView(R.id.batch_work_main_content_editShowWeightForTon)
    EditText editShowWeightForTon;//重量
    @BindView(R.id.batch_work_main_content_editShowVolumeForSquare)
    EditText editShowVolumeForSquare;//体积
    @BindView(R.id.batch_work_main_content_tvShowInventoryStatus)
    TextView tvShowInventoryStatus;//库存状态
    @BindView(R.id.batch_work_main_content_tvShowInventoryType)
    TextView tvShowInventoryType;//库存类型
    @BindView(R.id.batch_work_main_content_tvShowStandard)
    TextView tvShowStandard;//规格
    @BindView(R.id.batch_work_main_content_editShowBatchNumber)
    EditText editShowBatchNumber;//批次号

    OrderInAndOutBoundBean orderInAndOutBoundBean;//订单出入库对象

    InAndOutBoundLocationBean inAndOutBoundLocationBean;//出入库定位对象

    boolean isOrderInOrOutBound=true;//是否是订单出入库

    boolean isGetUIData=true;
    BatchLocationNoticeBean batchLocationNoticeBean;//批量作业界面获取的数据对象
    private int oldPosition;//记录上次所选物料的位置
    private int currentPosition;//记录当前所选物料的位置

    /**
     * 确认作业请求参数
     */
    String orderId="";
    String orderNo="";
    String noticeOrderId="";
    String noticeOrderNo="";
    WorkInfoBean materielPositionInfoBean;
    int operateType;
    boolean isShowNoticeUI=true;//是否是通知单UI界面

    HttpManger httpManger;
    boolean isGetUIMaterielDataEnd=false;
    boolean isGetUIMaterielDataSuccess=false;

    SearchStockBean currentSearchStockBean;//当前选中库位对象
//    SelectDictionaryBean currentSelectDictionaryBean;//当前选中仓库对象
    private String sumShowStr = "";

    ArrayList<WorkNotesBean> remarks;//作业记录

    @Override
    protected int getLayoutResource() {
        return R.layout.batch_work_main;
    }

    @Override
    protected void initView() {
        super.initView();
        showLeftBack();
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
        loadTipFailedLayout.setRestartOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                batchLocationByNoticeUI();
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        activityFlag=getIntent().getIntExtra(Constants.FLAG_ACTIVITY_KEY,  Constants.FLAG_ACTIVITY_COME_ORDER_IN_BOUND_DETAIL_UI);
        if (activityFlag==Constants.FLAG_ACTIVITY_COME_ORDER_IN_BOUND_DETAIL_UI | activityFlag==Constants.FLAG_ACTIVITY_COME_ORDER_OUT_BOUND_DETAIL_UI){
            setTitleShow(getResourcesString(R.string.order_batch_work));
            isShowNoticeUI=false;
            isOrderInOrOutBound=true;
        }else if (activityFlag==Constants.FLAG_ACTIVITY_COME_NOTICE_LETTER_OUT_BOUND_DETAIL_UI | activityFlag==Constants.FLAG_ACTIVITY_COME_NOTICE_LETTER_IN_BOUND_DETAIL_UI){
            setTitleShow(getResourcesString(R.string.notice_letter_batch_work));
            isShowNoticeUI=true;
            isOrderInOrOutBound=false;
        }

        if (activityFlag == Constants.FLAG_ACTIVITY_COME_ORDER_IN_BOUND_DETAIL_UI ||  activityFlag == Constants.FLAG_ACTIVITY_COME_NOTICE_LETTER_OUT_BOUND_DETAIL_UI) {
            sumShowStr = "未作业数量：";
        } else {
            sumShowStr = "未定位数量：";
        }
        showFourthTv.setText(sumShowStr);

        if (getIntent().hasExtra("OrderInAndOutBoundBean")){
            orderInAndOutBoundBean= (OrderInAndOutBoundBean) getIntent().getExtras().getSerializable("OrderInAndOutBoundBean");
        }else if (getIntent().hasExtra("InAndOutBoundLocationBean")){
            inAndOutBoundLocationBean= (InAndOutBoundLocationBean) getIntent().getExtras().getSerializable("InAndOutBoundLocationBean");
        }
        materielPositionInfoBean= (WorkInfoBean) getIntent().getSerializableExtra("WorkInfoBean");
        operateType=getIntent().getExtras().getInt("operateType");
        itemMaterielList=new ArrayList<>();
        itemList=new ArrayList<>();
        materielAdapterFlag=CommonNormalAdapter.FLAG_NOTICE_OR_ORDER_BATCH_WORK_MAIN_MATREIEL;
    }

    @Override
    protected void initListener() {
        super.initListener();
        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAllActivityExceptAppointed(MainActivity.class);
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(BatchWorkActivity.this, ScanActivity.class);
                startActivity(intent);
            }
        });
        tvSureWork.setOnClickListener(this);
        InterfaceUtil.getInstance().setInterfaceCallBackListener(interfacesCallBackListener);
    }

    InterfaceUtil.InterfacesCallBackListener  interfacesCallBackListener=new InterfaceUtil.InterfacesCallBackListener(){
        @Override
        public void onSuccess(BaseInfo<?> baseInfo) {
        }

        @Override
        public void onFailure(String message) {
        }

        @Override
        public void onSuccess(BaseInfo<?> baseInfo, Enum opertateFlagEnum) {
            if (opertateFlagEnum==OperateFlagEnum.BATCH_WORK_MATERIEL_DATA){
                List<MaterielBatchWorkBean> batchLocationNoticeList= (List<MaterielBatchWorkBean>) baseInfo.getData();
                //物料列表数据
                if (batchLocationNoticeList!=null && batchLocationNoticeList.size()>0){
                    isGetUIMaterielDataSuccess=true;
                    for (MaterielBatchWorkBean materielPositionInfoBean: batchLocationNoticeList){
                        itemList.add(new BaseItemBean(materielPositionInfoBean));
                    }
                }else {
                    isGetUIMaterielDataSuccess=false;
                }
            }else if (opertateFlagEnum==OperateFlagEnum.BATCH_LACATION_BASE_DATA){
            }
            if (!isGetUIMaterielDataSuccess){
                checkGetAllDataEnd(true ,"获取数据为空！");
            }else {
                loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FINISH);
                oldPosition = 0;
                currentPosition = 0;
                showMaterielInfo(0);
            }
        }

        @Override
        public void onFailure(String message, Enum opertateFlagEnum) {
            if (opertateFlagEnum==OperateFlagEnum.BATCH_WORK_MATERIEL_DATA){
                isGetUIMaterielDataEnd=true;
                isGetUIMaterielDataSuccess=false;
            }else if (opertateFlagEnum==OperateFlagEnum.BATCH_WORK_BASE_DATA){
            }
            checkGetAllDataEnd(false, message);
        }
    };


    /**
     * 获取物料数据失败或者获取基本数据信息失败时，展示无数据界面
     * @param isShowNoData
     * @param message
     */
    private void checkGetAllDataEnd(boolean isShowNoData , String message){
        loadTipFailedLayout.setTextColor(R.color.color_gray);
        if (isShowNoData){
            loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
            loadTipFailedLayout.setNormalText(R.string.noMessage);
            loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_NORMAL);
        }else {
            loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FAILED);
            loadTipFailedLayout.setNormalText(R.string.since_help_load_failed);
            loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        }
        ToastUtil.showToast(BatchWorkActivity.this, message);
    }

    @Override
    protected void initRecyclerView() {
        super.initRecyclerView();
        /**
         * 物料列表
         */
        RecyclerViewUtil.initLinearLayoutHorizontal(this, materielRecyclerView);
        materielAdapter= CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.materiel_position_info_item, itemList, materielAdapterFlag);
        materielAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                saveOldMaterielInfo(oldPosition);
                currentPosition = position;
                showMaterielInfo(position);
                oldPosition = position;
            }
        });
        materielRecyclerView.setAdapter(materielAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        httpManger=InterfaceUtil.getInstance().httpManger;
        isGetUIData=true;
        batchLocationByNoticeUI();
    }

    @OnClick({R.id.batch_work_main_tvSureWork,
            R.id.batch_work_main_content_tvShowInventoryStatus,
            R.id.batch_work_main_content_tvShowInventoryType,
            R.id.batch_work_main_content_tvShowStandard,
            R.id.batch_work_main_content_tvShowJobRecord,
            R.id.batch_work_main_content_tvShowReservoirPosition})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        int reqCode=-1;
        Intent intent=null;
        switch (v.getId()){
            case R.id.batch_work_main_tvSureWork://确认作业
                if (StringUtils.isEmpty(tvShowReservoirPosition.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastPleaseSeletedStockPosition));
                    return;
                }
                if (StringUtils.isEmpty(tvShowStorehouse.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastPleaseSeletedWareHouse));
                    return;
                }

                batchWorkUIByConfirmWork();
                break;
            case R.id.batch_work_main_content_tvShowInventoryStatus://库存状态
                intent = new Intent(this, SelectBaseDataActivity.class);
                reqCode = AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_STATUS;
                intent.putExtra("action", AppConfig.BaseDataAction.STO_INVENTORY_STOCK_STATUS);
                startActivityForResult(intent, reqCode);
                break;
            case R.id.batch_work_main_content_tvShowInventoryType://库存类型
                intent = new Intent(this, SelectBaseDataActivity.class);
                reqCode = AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_TYPE;
                intent.putExtra("action", AppConfig.BaseDataAction.STO_INVENTORY_STOCK_TYPE);
                startActivityForResult(intent, reqCode);
                break;
            case R.id.batch_work_main_content_tvShowStandard://规格
                intent = new Intent(this, SelectBaseDataActivity.class);
                reqCode = AppConfig.BaseDataAction.REQCODE_SKU_UNIT;
                intent.putExtra("action", AppConfig.BaseDataAction.WARE_SELECT_SKU_UNIT);
                intent.putExtra("skuId", materielPositionInfoBean.skuId);//物料ID
                startActivityForResult(intent, reqCode);
                break;
            case R.id.batch_work_main_content_tvShowJobRecord://作业记录
                intent = new Intent(this, OperateRemarkActivity.class);
                intent.putExtra("OperateRemark",remarks);
                intent.putExtra("TotolWeight",materielPositionInfoBean.detailWeight);
                startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_JOB_RECORD);
                break;
            case R.id.batch_work_main_content_tvShowReservoirPosition:
                intent= new Intent(this, DepotSelectActivity.class);
                if (activityFlag==Constants.FLAG_ACTIVITY_COME_ORDER_IN_BOUND_DETAIL_UI){
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_WORK_IN_BOUND_BY_DEPOT;
                }else {
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_WORK_OUT_BOUND_BY_DEPOT;
                }
                if (operateType == 0) {// 入库定位
                    intent.putExtra("showType", DepotSelectActivity.TYPE_IN_STOCK);
                } else {//出库定位
                    intent.putExtra("showType", DepotSelectActivity.TYPE_OUT_STOCK);
                }
                startActivityForResult(intent, reqCode);

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        MaterielBatchWorkBean materielPositionInfoBean = null;
        if (data != null && requestCode == AppConfig.BaseDataAction.REQCODE_JOB_RECORD) {
            remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");
            if (remarks == null || remarks.size() < 1) {
                return;
            }
            String workNoteName = "";
            for (int i = 0; i < remarks.size(); i++) {
                if (StringUtils.isBlank(workNoteName))
                    workNoteName = remarks.get(i).getDepart();
                else
                    workNoteName = workNoteName + "," + remarks.get(i).getDepart();
            }
            materielPositionInfoBean = (MaterielBatchWorkBean) itemList.get(currentPosition).object;
            materielPositionInfoBean.jobRecord = workNoteName;
            materielPositionInfoBean.jobInfoList = remarks;
            tvShowJobRecord.setText(materielPositionInfoBean.jobRecord);
        }

        if (data == null || data.getSerializableExtra("selectBean") == null)
            return;
        SelectDictionaryBean selectBean = null;
        switch (requestCode){
            case AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_STATUS://库存状态
                selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
                materielPositionInfoBean = (MaterielBatchWorkBean) itemList.get(currentPosition).object;
                if (materielPositionInfoBean != null){
                    materielPositionInfoBean.stockStatus = selectBean.getValue();
                    materielPositionInfoBean.stockStatusName = selectBean.getText();
                }
                break;
            case AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_TYPE:
                selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
                materielPositionInfoBean = (MaterielBatchWorkBean) itemList.get(currentPosition).object;
                if (materielPositionInfoBean != null){
                    materielPositionInfoBean.stockType = selectBean.getValue();
                    materielPositionInfoBean.stockTypeName = selectBean.getText();
                }
                break;
            case AppConfig.BaseDataAction.REQCODE_SKU_UNIT:
                selectBean= (SelectDictionaryBean) data.getSerializableExtra("selectBean");
                materielPositionInfoBean = (MaterielBatchWorkBean) itemList.get(currentPosition).object;
                if (materielPositionInfoBean != null){
                    materielPositionInfoBean.unitId = selectBean.getValue();
                    materielPositionInfoBean.unitName= selectBean.getText();
                }
                break;
            case AppConfig.BaseDataAction.REQCODE_BATCH_WORK_IN_BOUND:
            case AppConfig.BaseDataAction.REQCODE_BATCH_WORK_OUT_BOUND:
//                currentSelectDictionaryBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
//                tvShowStorehouse.setText(currentSelectDictionaryBean.getText());
                break;
            case AppConfig.BaseDataAction.REQCODE_BATCH_WORK_IN_BOUND_BY_DEPOT:
            case AppConfig.BaseDataAction.REQCODE_BATCH_WORK_OUT_BOUND_BY_DEPOT:
                currentSearchStockBean= (SearchStockBean) data.getSerializableExtra("selectBean");
                tvShowReservoirPosition.setText(currentSearchStockBean.getStockName());
                tvShowStorehouse.setText(currentSearchStockBean.getWhName());
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 通知单批量定位数据
     */
    private void batchLocationByNoticeUI(){
        loadTipFailedLayout.setLoadText(R.string.since_help_loading);
        loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_PROGRESS);
        String noticeOrderIdOrOrderId="";
        if (isOrderInOrOutBound){
            noticeOrderIdOrOrderId=getStringByIsEmpty(orderInAndOutBoundBean.orderId);
        }else{
            noticeOrderIdOrOrderId=getStringByIsEmpty(inAndOutBoundLocationBean.noticeOrderId);
        }
        InterfaceUtil.getInstance().batchWorkByNoticeUI(noticeOrderIdOrOrderId, OperateFlagEnum.BATCH_WORK_MATERIEL_DATA, this, isShowNoticeUI);
    }

    private void batchWorkUIByConfirmWork(){
        if (itemList == null || itemList.size() == 0) {
            return;
        }
        List<BaseItemBean> saveList = new ArrayList<>();
        MaterielBatchWorkBean orgItem = null;
        BaseItemBean orgBean = null;
        for (int i = 0; i < itemList.size(); i++) {
            orgBean = itemList.get(i);
            orgItem = (MaterielBatchWorkBean) orgBean.object;
            if ((orgItem.actualAmount.compareTo(BigDecimal.ZERO) == 0)
                    && (orgItem.actualWeight.compareTo(BigDecimal.ZERO) == 0)
                    && (orgItem.actualVolume.compareTo(BigDecimal.ZERO) == 0)) {
                continue;
            }
            saveList.add(orgBean);
        }
        httpManger.setContext(this);
        httpManger.batchWorkUIByConfirmWork(saveList);
        httpManger.setHttpResponseCallBackListener(this);
    }

    @Override
    public void onSuccess(BaseInfo<?> baseInfo) {
        super.onSuccess(baseInfo);
    }

    @Override
    public void onFailure(String message) {
        super.onFailure(message);
    }

    private void saveOldMaterielInfo(int old) {
        if (itemList.size()<=0){
            return;
        }
        MaterielBatchWorkBean materielPositionInfoBean= (MaterielBatchWorkBean) itemList.get(old).object;
        if (materielPositionInfoBean!=null){
            try {
                materielPositionInfoBean.actualAmount = new BigDecimal(editShowNumberForPiece.getText().toString());
                materielPositionInfoBean.actualWeight = new BigDecimal(editShowWeightForTon.getText().toString());
                materielPositionInfoBean.actualVolume = new BigDecimal(editShowVolumeForSquare.getText().toString());
            } catch (Exception e) {
                ToastUtil.showToast(BatchWorkActivity.this, "数量等信息转换失败");
            }
        }
    }
    private void showMaterielInfo(int currentPosition){
        if (itemList.size()<=0){
            return;
        }
        MaterielBatchWorkBean materielPositionInfoBean= (MaterielBatchWorkBean) itemList.get(currentPosition).object;
        if (materielPositionInfoBean!=null){
            showFirstValue.setText(materielPositionInfoBean.skuCode);
            showSecondValue.setText(materielPositionInfoBean.skuName);
            showThirdValue.setText(materielPositionInfoBean.detailAmount+"件/"+materielPositionInfoBean.detailWeight+"吨");
            showFourthValue.setText(materielPositionInfoBean.notJobAmount+"件/"+materielPositionInfoBean.notJobWeight+"吨");
            tvWorkInfo.setText(sumShowStr+materielPositionInfoBean.detailAmount+"件/"+materielPositionInfoBean.detailWeight+"吨");

            editShowNumberForPiece.setText(materielPositionInfoBean.actualAmount.toString());
            editShowWeightForTon.setText(materielPositionInfoBean.actualWeight.toString());
            editShowVolumeForSquare.setText(materielPositionInfoBean.actualVolume.toString());

            tvShowInventoryStatus.setText(materielPositionInfoBean.stockStatusName);
            tvShowInventoryType.setText(materielPositionInfoBean.stockTypeName);
            tvShowStandard.setText(materielPositionInfoBean.unitName);
        }

        for (BaseItemBean baseItemBean : itemList){
            ((MaterielBatchWorkBean)baseItemBean.object).isSelected=false;
        }
        ((MaterielBatchWorkBean) itemList.get(currentPosition).object).isSelected=true;
        materielAdapter.setNewData(itemList);
    }

}
